package top.frsf.rpc.loadbalance.impl;

import top.frsf.rpc.entity.ServiceInstance;
import top.frsf.rpc.enums.LoadBalanceEnum;
import top.frsf.rpc.loadbalance.LoadBalance;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author He Kuntao
 * @since 2025/7/18 10:03
 */
public class RoundRobinLoadBalance implements LoadBalance {
    /**
     * 轮询计数器
     */
    private final AtomicInteger counter = new AtomicInteger(0);

    @Override
    public ServiceInstance select(List<ServiceInstance> instances) {
        // 取模防止负数
        int index = counter.getAndIncrement() % instances.size();
        if (index < 0) {
            index = -index;
            counter.set(0);
        }
        return instances.get(index);
    }

    @Override
    public LoadBalanceEnum getLoadBalanceEnum() {
        return LoadBalanceEnum.ROUND_ROBIN;
    }
}
